from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
X, y = make_blobs(n_samples=300,  # 样本数量
                  centers=4,  # 聚类中心数量
                  random_state=np.random.randint(1, 1000))  # 随机种子

kmeans = KMeans(n_clusters=4, random_state=0).fit(X)
kmeans.fit(X)
y_pred=kmeans.predict(X)
centroids = kmeans.cluster_centers_

# 可视化
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis', edgecolors='k')
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.5, marker='X', label="Centroids")
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Clustering Data')
plt.show()
